package com.controller.device;

import com.common.ErrorCodeEnum;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.excel.ExcelUtil;
import com.common.exception.BusinessException;
import com.common.utils.Constants;
import com.common.utils.DateUtils;
import com.common.utils.EntityConversionUtil;
import com.common.utils.StringUtils;
import com.common.utils.file.FileUtils;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.github.pagehelper.PageInfo;
import com.model.base.PageResult;
import com.model.base.Result;
import com.model.domain.device.*;
import com.model.domain.system.GetSystemDeviceModelInfoDO;
import com.model.domain.system.GetSystemDomainInfoDO;
import com.model.dto.device.deviceOBDInfo.CheckCartonNoDTO;
import com.model.dto.device.deviceOBDInfo.ExportDeviceListByBatchDTO;
import com.model.dto.device.devicePCBInfo.*;
import com.model.pojo.device.*;
import com.model.pojo.sys.SysUser;
import com.model.pojo.system.SimInfo;
import com.model.pojo.system.SystemDeviceModelInfo;
import com.model.pojo.system.SystemDomainInfo;
import com.model.vo.device.deviceOBDInfo.exportDeviceListByBatch.ExportDeviceListByBatchVO;
import com.model.vo.device.deviceOBDInfo.vail3Code.Vail3CodeVO;
import com.model.vo.device.devicePCBInfo.getBatchList.GetBatchListVO;
import com.model.vo.device.devicePCBInfo.getDeviceDtuPoolList.GetDeviceDtuPoolListVO;
import com.model.vo.device.devicePCBInfo.getDeviceList.GetDeviceListVO;
import com.model.vo.device.devicePCBInfo.getDeviceSimPoolList.GetDeviceSimPoolListVO;
import com.model.vo.device.devicePCBInfo.getDeviceSimRecordList.GetDeviceSimRecordListVO;
import com.model.vo.device.devicePCBInfo.getErrorInfoByDtu.GetErrorInfoByDtuVO;
import com.model.vo.device.devicePCBInfo.getErrorRecordList.GetErrorRecordListVO;
import com.model.vo.device.devicePCBInfo.getGpsMonitorList.GetGpsMonitorListVO;
import com.model.vo.device.devicePCBInfo.getModuleErrorInfoByDtu.GetModuleErrorInfoByDtuVO;
import com.model.vo.device.devicePCBInfo.getModuleErrorRecordList.GetModuleErrorRecordListVO;
import com.model.vo.device.devicePCBInfo.getNewImage.GetNewImageVO;
import com.model.vo.device.devicePCBInfo.getNewImgInfo.GetNewImgInfoVO;
import com.model.vo.device.devicePCBInfo.getSensorErrorInfoByDtu.GetSensorErrorInfoByDtuVO;
import com.model.vo.device.devicePCBInfo.getSensorList.GetSensorListVO;
import com.model.vo.device.devicePCBInfo.getStatisticsInfo.GetStatisticsInfoVO;
import com.model.vo.device.devicePCBInfo.getVersionList.GetVersionListVO;
import com.model.vo.device.devicePCBInfo.saveDtuToPool.SaveDtuToPoolErrorVO;
import com.model.vo.device.devicePCBInfo.saveRepairInfo.SaveRepairInfoVO;
import com.model.vo.device.devicePCBInfo.saveSimToPool.SaveSimToPoolErrorVO;
import com.model.vo.device.devicePCBInfo.scanBeforeExFactory.ScanBeforeExFactoryDeviceVO;
import com.model.vo.device.devicePCBInfo.scanBeforeExFactory.ScanBeforeExFactoryVO;
import com.model.vo.device.devicePCBInfo.statisticsSimExpireInfo.StatisticsSimExpireInfoVO;
import com.model.vo.device.devicePCBInfo.submitPhoto.SubmitPhotoVO;
import com.service.device.*;
import com.service.system.SimInfoService;
import com.service.system.SystemDeviceModelInfoService;
import com.service.system.SystemDomainInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-06-07 1:10
 **/
@Api(tags = {"PCB终端管理"})
@Slf4j
@RestController
@RequestMapping("/v1/device/pcb")
@RequiredArgsConstructor
public class DevicePCBInfoController {
    private final DevicePcbBaseInfoService devicePcbBaseInfoService;
    private final DevicePcbSensorInfoService devicePcbSensorInfoService;
    private final DevicePcbErrorRecordInfoService devicePcbErrorRecordInfoService;
    private final DevicePcbVersionInfoService devicePcbVersionInfoService;
    private final DevicePcbGpsInfoService devicePcbGpsInfoService;
    private final DevicePcbGpsImgInfoService devicePcbGpsImgInfoService;
    private final DevicePcbRepairRecordInfoService devicePcbRepairRecordInfoService;
    private final DevicePcbExFactoryBatchInfoService devicePcbExFactoryBatchInfoService;
    private final DevicePcbErrorInfoService devicePcbErrorInfoService;
    private final DevicePcbModuleErrorInfoService devicePcbModuleErrorInfoService;
    private final DevicePcbModuleErrorRecordInfoService devicePcbModuleErrorRecordInfoService;
    private final DevicePcbSimRecordInfoService devicePcbSimRecordInfoService;
    private final DevicePcbExFactoryDtuPoolInfoService devicePcbExFactoryDtuPoolInfoService;
    private final DevicePcbExFactorySimPoolInfoService devicePcbExFactorySimPoolInfoService;
    private final SystemDomainInfoService systemDomainInfoService;
    private final SystemDeviceModelInfoService systemDeviceModelInfoService;
    private final SimInfoService simInfoService;
    private final DevicePcbBjBaseInfoService devicePcbBjBaseInfoService;
    private final DevicePcbExFactoryScanRecordInfoService devicePcbExFactoryScanRecordInfoService;

    @Log(title = "PCB终端管理-终端统计信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "终端统计信息")
    @PostMapping("/getStatisticsInfo")
    public Result<GetStatisticsInfoVO> getStatisticsInfo() {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        Integer total = 0;
        Integer online = 0;
        Integer offline = 0;
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
        if (sysUser.getUserType() != Constants.SysUserUserType.TYPE_管理员 && sysUser.getUserType() != Constants.SysUserUserType.TYPE_车间生产) {
            getDevicePcbBaseInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        List<DevicePcbBaseInfo> deviceList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            total = deviceList.size();
            for (DevicePcbBaseInfo baseInfo : deviceList) {
                if (baseInfo.getOnLineStatus() == null || baseInfo.getOnLineStatus() == 0) {
                    offline++;
                } else online++;
            }
        }
        GetStatisticsInfoVO vo = new GetStatisticsInfoVO();
        vo.setTotal(total);
        vo.setOffline(offline);
        vo.setOnline(online);
        return Result.suc(vo);
    }

    @Log(title = "PCB终端管理-安卓版终端列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "安卓版终端列表")
    @PostMapping("/getDeviceList")
    public Result<PageResult<List<GetDeviceListVO>>> getPcbDeviceList(@RequestBody @Valid GetDeviceListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceListVO> voList = new ArrayList<>();
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbBaseInfoDO.class);
        if (sysUser.getUserType() != Constants.SysUserUserType.TYPE_管理员 && sysUser.getUserType() != Constants.SysUserUserType.TYPE_车间生产) {
            getDevicePcbBaseInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        getDevicePcbBaseInfoDO.setSortRow("onLineStatus");
        getDevicePcbBaseInfoDO.setSortOrder("desc");
        List<DevicePcbBaseInfo> deviceList = devicePcbBaseInfoService.getPageList(getDevicePcbBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            Map<Long, SystemDeviceModelInfo> modelMap = new HashMap<>();
            deviceList.forEach(item -> {
                String batchNo = "";
                String exDate = "";
                String modelName = "";
                GetDeviceListVO vo = EntityConversionUtil.copy(item, GetDeviceListVO.class);
                vo.setDeviceId(item.getId());
                if (item.getBatchId() != null && item.getBatchId() > 0) {
                    DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(item.getBatchId());
                    if (batchInfo != null) {
                        batchNo = batchInfo.getBatchNo();
                        if (batchInfo.getExDate() != null) {
                            exDate = DateUtils.parseDateToStr(batchInfo.getExDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                        }
                    }
                    SystemDeviceModelInfo modelInfo = modelMap.get(item.getBatchId());
                    if (modelInfo == null) {
                        if (batchInfo != null && batchInfo.getModelId() != null) {
                            modelInfo = systemDeviceModelInfoService.getById(batchInfo.getModelId());
                            if (modelInfo != null) {
                                modelMap.put(item.getBatchId(), modelInfo);
                                modelName = modelInfo.getName();
                            }
                        }
                    } else {
                        modelName = modelInfo.getName();
                    }
                }
                vo.setBatchNo(batchNo);
                vo.setExDate(exDate);
                vo.setModelName(modelName);
                voList.add(vo);
            });
        }
        PageInfo<DevicePcbBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListVO>> build = PageResult.<List<GetDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "PCB终端管理-北京O8安卓版终端列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "北京O8安卓版终端列表")
    @PostMapping("/getDeviceListOfBj")
    public Result<PageResult<List<GetDeviceListVO>>> getDeviceListOfBj(@RequestBody @Valid GetDeviceListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceListVO> voList = new ArrayList<>();
        GetDevicePcbBjBaseInfoDO getDevicePcbBjBaseInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbBjBaseInfoDO.class);
        if (sysUser.getUserType() != Constants.SysUserUserType.TYPE_管理员 && sysUser.getUserType() != Constants.SysUserUserType.TYPE_车间生产) {
            getDevicePcbBjBaseInfoDO.setFactoryUserId(sysUser.getUserId());
        }
        getDevicePcbBjBaseInfoDO.setSortRow("id");
        getDevicePcbBjBaseInfoDO.setSortOrder("desc");
        List<DevicePcbBjBaseInfo> deviceList = devicePcbBjBaseInfoService.getPageList(getDevicePcbBjBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            Map<Long, SystemDeviceModelInfo> modelMap = new HashMap<>();
            deviceList.forEach(item -> {
                String batchNo = "";
                String exDate = "";
                String modelName = "";
                GetDeviceListVO vo = EntityConversionUtil.copy(item, GetDeviceListVO.class);
                vo.setDeviceId(item.getId());
                if (item.getBatchId() != null && item.getBatchId() > 0) {
                    DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(item.getBatchId());
                    if (batchInfo != null) {
                        batchNo = batchInfo.getBatchNo();
                        if (batchInfo.getExDate() != null) {
                            exDate = DateUtils.parseDateToStr(batchInfo.getExDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                        }
                    }
                    SystemDeviceModelInfo modelInfo = modelMap.get(item.getBatchId());
                    if (modelInfo == null) {
                        if (batchInfo != null && batchInfo.getModelId() != null) {
                            modelInfo = systemDeviceModelInfoService.getById(batchInfo.getModelId());
                            if (modelInfo != null) {
                                modelMap.put(item.getBatchId(), modelInfo);
                                modelName = modelInfo.getName();
                            }
                        }
                    } else {
                        modelName = modelInfo.getName();
                    }
                }
                vo.setBatchNo(batchNo);
                vo.setExDate(exDate);
                vo.setModelName(modelName);
                voList.add(vo);
            });
        }
        PageInfo<DevicePcbBjBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListVO>> build = PageResult.<List<GetDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "PCB终端管理-传感器列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "传感器列表")
    @PostMapping("/getSensorList")
    public Result<List<GetSensorListVO>> getSensorList(@RequestBody @Valid GetSensorListDTO dto) {
        List<GetSensorListVO> voList = new ArrayList<>();
        DevicePcbBaseInfo deviceInfo = devicePcbBaseInfoService.getById(dto.getDeviceId());
        if (deviceInfo == null) {
            return Result.fail("9999", "设备不存在");
        }
        GetDevicePcbSensorInfoDO getDevicePcbSensorInfoDO = new GetDevicePcbSensorInfoDO();
//        getDevicePcbSensorInfoDO.setDtu(deviceInfo.getDtu());
//        getDevicePcbSensorInfoDO.setShortDtu(deviceInfo.getDtu().substring(deviceInfo.getDtu().length() - 5, deviceInfo.getDtu().length()));
        getDevicePcbSensorInfoDO.setDeviceId(deviceInfo.getId());
        getDevicePcbSensorInfoDO.setSortRow("createTime");
        List<DevicePcbSensorInfo> sensorList = devicePcbSensorInfoService.getAllList(getDevicePcbSensorInfoDO);
        if (sensorList != null && sensorList.size() > 0) {
            sensorList.forEach(item -> {
                GetSensorListVO vo = EntityConversionUtil.copy(item, GetSensorListVO.class);
                vo.setCurVersion(deviceInfo.getCurVersion());
                vo.setImei(deviceInfo.getImei());
                vo.setSim(deviceInfo.getSim());
                vo.setSensorType(item.getSensorType());
                Map<String, String> sensorMap = getSensorMap();
                vo.setSensorName(sensorMap.get(item.getSensorType()));
                String data1 = item.getFitZeroData1();
                String data2 = item.getFitZeroData2();
                int fitZeroStatus = 0;
                if (data1 == null) data1 = "";
                if (data2 == null) data2 = "";
                if (item.getFitZeroStatus() != null) fitZeroStatus = item.getFitZeroStatus();
                vo.setData1(data1);
                vo.setData2(data2);
                vo.setFitZeroStatus(fitZeroStatus);
                voList.add(vo);
            });
        }
        return Result.suc(voList);
    }


    @Log(title = "PCB终端管理-定位监控", businessType = BusinessType.SELECT)
    @ApiOperation(value = "定位监控")
    @PostMapping("/getGpsMonitorList")
    public Result<PageResult<List<GetGpsMonitorListVO>>> getGpsMonitorList(@RequestBody @Valid GetGpsMonitorListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetGpsMonitorListVO> voList = new ArrayList<>();
        List<DevicePcbGpsInfo> gpsList = new ArrayList<>();
        GetDevicePcbGpsInfoDO getDevicePcbGpsInfoDO = new GetDevicePcbGpsInfoDO();
        if (sysUser.getUserType() != Constants.SysUserUserType.TYPE_管理员 && sysUser.getUserType() != Constants.SysUserUserType.TYPE_车间生产) {
            List<String> shortDtuList = new ArrayList<>();
            shortDtuList.add("0");
            GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
            getDevicePcbBaseInfoDO.setFactoryUserId(sysUser.getUserId());
            getDevicePcbBaseInfoDO.setSortRow("id");
            List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
            if (baseList != null && baseList.size() > 0) {
                shortDtuList = baseList.stream().map(DevicePcbBaseInfo::getShortDtu).collect(Collectors.toList());
            }
            getDevicePcbGpsInfoDO.setShortDtus(shortDtuList);
        }
        if (dto.getDataType() == 1) {//正常
            if (StringUtils.isNotBlank(dto.getShortDtu())) {
                getDevicePcbGpsInfoDO.setShortDtu(dto.getShortDtu().substring(dto.getShortDtu().length() - 5, dto.getShortDtu().length()));
            }
//            getDevicePcbGpsInfoDO.setDtu(dto.getDtu());
            String tableName = "device_pcb_gps_info_";
            getDevicePcbGpsInfoDO.setPage(dto.getPage());
            getDevicePcbGpsInfoDO.setPageSize(dto.getPageSize());
            getDevicePcbGpsInfoDO.setSTime(dto.getStartTime());
            getDevicePcbGpsInfoDO.setETime(dto.getEndTime());
            tableName += dto.getStartTime().split(" ")[0].replaceAll("-", "");
            getDevicePcbGpsInfoDO.setSortRow("time");
            getDevicePcbGpsInfoDO.setSortOrder("desc");
            getDevicePcbGpsInfoDO.setTableName(tableName);
            gpsList = devicePcbGpsInfoService.getPageList(getDevicePcbGpsInfoDO);
        } else {//断点
            if (StringUtils.isNotBlank(dto.getShortDtu())) {
                getDevicePcbGpsInfoDO.setShortDtu(dto.getShortDtu().substring(dto.getShortDtu().length() - 5, dto.getShortDtu().length()));
            }
//            getDevicePcbGpsInfoDO.setDtu(dto.getDtu());
            String tableName = "device_pcb_gps_info_";
            getDevicePcbGpsInfoDO.setPage(dto.getPage());
            getDevicePcbGpsInfoDO.setPageSize(dto.getPageSize());
            getDevicePcbGpsInfoDO.setSTime(dto.getStartTime());
            getDevicePcbGpsInfoDO.setETime(dto.getEndTime());
            tableName += dto.getStartTime().split(" ")[0].replaceAll("-", "");
            getDevicePcbGpsInfoDO.setSortRow("time");
            getDevicePcbGpsInfoDO.setSortOrder("desc");
            getDevicePcbGpsInfoDO.setTableName(tableName);
            List<DevicePcbGpsInfo> tempGpsList = devicePcbGpsInfoService.getAllList(getDevicePcbGpsInfoDO);
            if (tempGpsList != null && tempGpsList.size() > 0) {
                DevicePcbGpsInfo info2 = tempGpsList.get(0);
                for (int i = 1; i < tempGpsList.size(); i++) {
                    DevicePcbGpsInfo info1 = tempGpsList.get(i);
                    Date date1 = info1.getTime();
                    Date date2 = info2.getTime();
                    long second = DateUtils.calSecond(date1, date2);
                    if (second > dto.getBreakPoint()) {
                        gpsList.add(info2);
                        gpsList.add(info1);
                    }
                    info2 = info1;
                }
            }
        }
        if (gpsList != null && gpsList.size() > 0) {
            gpsList.forEach(item -> {
                GetGpsMonitorListVO vo = EntityConversionUtil.copy(item, GetGpsMonitorListVO.class);
                vo.setDtu(item.getDtu().substring(1, item.getDtu().length()));
                BigDecimal speed = BigDecimal.ZERO;
                if (StringUtils.isNotBlank(item.getSpeed())) {
                    speed = new BigDecimal(item.getSpeed()).multiply(new BigDecimal(1.852)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
                }
                vo.setSpeed(speed);
                voList.add(vo);
            });
        }
//        voList = EntityConversionUtil.copyList(gpsList,GetGpsMonitorListVO.class);
        PageInfo<DevicePcbGpsInfo> pageInfo = new PageInfo<>(gpsList);
        PageResult<List<GetGpsMonitorListVO>> build = PageResult.<List<GetGpsMonitorListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "PCB终端管理-拍照", businessType = BusinessType.INSERT)
    @ApiOperation(value = "拍照")
    @PostMapping("/getNewImgInfo")
    public Result<GetNewImgInfoVO> getNewImgInfo(@RequestBody @Valid GetNewImgInfoDTO dto) {
        String shortDtu = "";
        String dtu = dto.getDtu();
        if (dtu.length() == 10 || dtu.length() == 16) {
            shortDtu = "Y-" + dtu.substring(dtu.length() - 5, dtu.length());
        } else if (dtu.length() == 11) {
            shortDtu = "Y=" + dtu.substring(dtu.length() - 5, dtu.length());
        }
        GetNewImgInfoVO vo = new GetNewImgInfoVO();
        GetDevicePcbGpsImgInfoDO getDevicePcbGpsImgInfoDO = new GetDevicePcbGpsImgInfoDO();
        getDevicePcbGpsImgInfoDO.setShortDtu(shortDtu);
        getDevicePcbGpsImgInfoDO.setImgPosition("2");//前置
        String tableName = "device_pcb_gps_img_info_";
        Date date = new Date();
        String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date) + " 00:00:00";
        String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date) + " 23:59:59";
        tableName += DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date).replaceAll("-", "");
        getDevicePcbGpsImgInfoDO.setSortRow("time");
        getDevicePcbGpsImgInfoDO.setSortOrder("desc");
        getDevicePcbGpsImgInfoDO.setTableName(tableName);
        String img1 = "";
        String time1 = "";
        String img2 = "";
        String time2 = "";
        List<DevicePcbGpsImgInfo> gpsList = devicePcbGpsImgInfoService.getPageList(getDevicePcbGpsImgInfoDO);
        if (gpsList != null && gpsList.size() > 0) {
            DevicePcbGpsImgInfo info = gpsList.get(0);
            time1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, info.getTime());
            if (!info.getImgSrc().startsWith("http")) {
                img1 = "http://39.108.117.16:8866" + info.getImgSrc();
            } else {
                img1 = info.getImgSrc();
            }
        }
        vo.setImg1(img1);
        vo.setTime1(time1);
        getDevicePcbGpsImgInfoDO.setImgPosition("1");//后置
        gpsList = devicePcbGpsImgInfoService.getPageList(getDevicePcbGpsImgInfoDO);
        if (gpsList != null && gpsList.size() > 0) {
            DevicePcbGpsImgInfo info = gpsList.get(0);
            time2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, info.getTime());
            if (!info.getImgSrc().startsWith("http"))
                img2 = "http://39.108.117.16:8866" + info.getImgSrc();
            else
                img2 = info.getImgSrc();
        }
        vo.setImg2(img2);
        vo.setTime2(time2);
        return Result.suc(vo);
    }

    @Log(title = "PCB终端管理-重启设备和APP", businessType = BusinessType.INSERT)
    @ApiOperation(value = "重启设备和APP")
    @PostMapping("/restartDevice")
    public Result<Objects> restartDevice(@RequestBody @Valid RestartDeviceDTO dto) {
        DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getByDtu(dto.getDtu());
        if (baseInfo == null) {
            return Result.fail("9999", "设备不存在");
        }
        if (dto.getType() == 1) {
            baseInfo.setSuperResetSwitch(1);
        } else if (dto.getType() == 2) {
            baseInfo.setSuperBootSwitch(1);
        }
        devicePcbBaseInfoService.update(baseInfo);
        return Result.suc();
    }

    @Log(title = "PCB终端管理-获取异常信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取异常信息")
    @PostMapping("/getErrorRecordList")
    public Result<PageResult<List<GetErrorRecordListVO>>> getErrorRecordList(@RequestBody @Valid GetErrorRecordListDTO dto) {
        List<GetErrorRecordListVO> voList = new ArrayList<>();
        GetDevicePcbErrorRecordInfoDO getDevicePcbErrorRecordInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbErrorRecordInfoDO.class);
        if (dto.getStartTime() != null && !"".equals(dto.getStartTime())) {
            getDevicePcbErrorRecordInfoDO.setStartTime(DateUtils.parseStrToDate(dto.getStartTime() + " 00:00:00", DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        if (dto.getEndTime() != null && !"".equals(dto.getEndTime())) {
            getDevicePcbErrorRecordInfoDO.setEndTime(DateUtils.parseStrToDate(dto.getEndTime() + " 23:59:59", DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
//        getDevicePcbErrorRecordInfoDO.setStatus(1);//异常
        getDevicePcbErrorRecordInfoDO.setSortRow("dataTime");
        List<DevicePcbErrorRecordInfo> recordList = devicePcbErrorRecordInfoService.getPageList(getDevicePcbErrorRecordInfoDO);
        if (recordList != null && recordList.size() > 0) {
            voList = EntityConversionUtil.copyList(recordList, GetErrorRecordListVO.class);
        }
        PageInfo<DevicePcbErrorRecordInfo> pageInfo = new PageInfo<>(recordList);
        PageResult<List<GetErrorRecordListVO>> build = PageResult.<List<GetErrorRecordListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "PCB终端管理-获取模块异常信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取模块异常信息")
    @PostMapping("/getModuleErrorRecordList")
    public Result<PageResult<List<GetModuleErrorRecordListVO>>> getModuleErrorRecordList(@RequestBody @Valid GetModuleErrorRecordListDTO dto) {
        List<GetModuleErrorRecordListVO> voList = new ArrayList<>();
        GetDevicePcbModuleErrorRecordInfoDO getDevicePcbModuleErrorRecordInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbModuleErrorRecordInfoDO.class);
        if (dto.getStartTime() != null && !"".equals(dto.getStartTime())) {
            getDevicePcbModuleErrorRecordInfoDO.setStartTime(DateUtils.parseStrToDate(dto.getStartTime() + " 00:00:00", DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        if (dto.getEndTime() != null && !"".equals(dto.getEndTime())) {
            getDevicePcbModuleErrorRecordInfoDO.setEndTime(DateUtils.parseStrToDate(dto.getEndTime() + " 23:59:59", DateUtils.YYYY_MM_DD_HH_MM_SS));
        }
        List<DevicePcbModuleErrorRecordInfo> recordList = devicePcbModuleErrorRecordInfoService.getPageList(getDevicePcbModuleErrorRecordInfoDO);
        if (recordList != null && recordList.size() > 0) {
            voList = EntityConversionUtil.copyList(recordList, GetModuleErrorRecordListVO.class);
        }
        PageInfo<DevicePcbModuleErrorRecordInfo> pageInfo = new PageInfo<>(recordList);
        PageResult<List<GetModuleErrorRecordListVO>> build = PageResult.<List<GetModuleErrorRecordListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-获取设备异常信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取设备异常信息")
    @PostMapping("/getErrorInfoByDtu")
    public Result<PageResult<List<GetErrorInfoByDtuVO>>> getErrorInfoByDtu(@RequestBody @Valid GetErrorInfoByDtuDTO dto) {
        List<GetErrorInfoByDtuVO> voList = new ArrayList<>();
        GetDevicePcbErrorInfoDO getDevicePcbErrorInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbErrorInfoDO.class);
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        if (sysUser.getUserType() != Constants.SysUserUserType.TYPE_管理员 && sysUser.getUserType() != Constants.SysUserUserType.TYPE_车间生产) {
            List<String> dtuList = new ArrayList<>();
            dtuList.add("0");
            GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbBaseInfoDO.class);
            getDevicePcbBaseInfoDO.setFactoryUserId(sysUser.getUserId());
            getDevicePcbBaseInfoDO.setSortRow("id");
            List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
            if (baseList != null && baseList.size() > 0) {
                dtuList = baseList.stream().map(DevicePcbBaseInfo::getDtu).collect(Collectors.toList());
            }
            getDevicePcbErrorInfoDO.setDtuList(dtuList);
        }
        getDevicePcbErrorInfoDO.setSortRow("lastModifiedTime");
        List<DevicePcbErrorInfo> list = devicePcbErrorInfoService.getPageList(getDevicePcbErrorInfoDO);
        if (list != null && list.size() > 0) {
            list.forEach(item -> {
                GetErrorInfoByDtuVO vo = EntityConversionUtil.copy(item, GetErrorInfoByDtuVO.class);
                String curVersion = "";
                DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getByDtu(item.getDtu());
                if (baseInfo != null && baseInfo.getCurVersion() != null) {
                    curVersion = baseInfo.getCurVersion();
                }
                vo.setCurVersion(curVersion);
                voList.add(vo);
            });
        }

        PageInfo<DevicePcbErrorInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetErrorInfoByDtuVO>> build = PageResult.<List<GetErrorInfoByDtuVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-获取设备传感器异常信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取设备传感器异常信息")
    @PostMapping("/getSensorErrorInfoByDtu")
    public Result<PageResult<List<GetSensorErrorInfoByDtuVO>>> getSensorErrorInfoByDtu(@RequestBody @Valid GetErrorInfoByDtuDTO dto) {
        List<GetSensorErrorInfoByDtuVO> voList = new ArrayList<>();
        GetDevicePcbErrorInfoDO getDevicePcbErrorInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbErrorInfoDO.class);
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        if (sysUser.getUserType() != Constants.SysUserUserType.TYPE_管理员 && sysUser.getUserType() != Constants.SysUserUserType.TYPE_车间生产) {
            List<String> dtuList = new ArrayList<>();
            dtuList.add("0");
            GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbBaseInfoDO.class);
            getDevicePcbBaseInfoDO.setFactoryUserId(sysUser.getUserId());
            getDevicePcbBaseInfoDO.setSortRow("id");
            List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
            if (baseList != null && baseList.size() > 0) {
                dtuList = baseList.stream().map(DevicePcbBaseInfo::getDtu).collect(Collectors.toList());
            }
            getDevicePcbErrorInfoDO.setDtuList(dtuList);
        }
        getDevicePcbErrorInfoDO.setSortRow("lastModifiedTime");
        getDevicePcbErrorInfoDO.setHasStatus4(1);
        List<DevicePcbErrorInfo> list = devicePcbErrorInfoService.getPageList(getDevicePcbErrorInfoDO);
        if (list != null && list.size() > 0) {
            list.forEach(item -> {
                GetSensorErrorInfoByDtuVO vo = EntityConversionUtil.copy(item, GetSensorErrorInfoByDtuVO.class);
                String curVersion = "";
                DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getByDtu(item.getDtu());
                if (baseInfo != null && baseInfo.getCurVersion() != null) {
                    curVersion = baseInfo.getCurVersion();
                }
                vo.setCurVersion(curVersion);
                voList.add(vo);
            });
        }

        PageInfo<DevicePcbErrorInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetSensorErrorInfoByDtuVO>> build = PageResult.<List<GetSensorErrorInfoByDtuVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-获取设备异常信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "获取设备异常信息")
    @PostMapping("/getModuleErrorInfoByDtu")
    public Result<PageResult<List<GetModuleErrorInfoByDtuVO>>> getModuleErrorInfoByDtu(@RequestBody @Valid GetModuleErrorInfoByDtuDTO dto) {
        List<GetModuleErrorInfoByDtuVO> voList = new ArrayList<>();
        GetDevicePcbModuleErrorInfoDO getDevicePcbModuleErrorInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbModuleErrorInfoDO.class);
        getDevicePcbModuleErrorInfoDO.setSortRow("lastModifiedTime");
        List<DevicePcbModuleErrorInfo> list = devicePcbModuleErrorInfoService.getPageList(getDevicePcbModuleErrorInfoDO);
        if (list != null && list.size() > 0) {
            voList = EntityConversionUtil.copyList(list, GetModuleErrorInfoByDtuVO.class);
        }

        PageInfo<DevicePcbModuleErrorInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetModuleErrorInfoByDtuVO>> build = PageResult.<List<GetModuleErrorInfoByDtuVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-版本列表", businessType = BusinessType.SELECT)
    @ApiOperation(value = "版本列表")
    @PostMapping("/getVersionList")
    public Result<PageResult<List<GetVersionListVO>>> getVersionList(@RequestBody @Valid GetVersionListDTO dto) {
        List<GetVersionListVO> voList = new ArrayList<>();
        GetDevicePcbVersionInfoDO getDevicePcbVersionInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbVersionInfoDO.class);
        getDevicePcbVersionInfoDO.setSortRow("createTime");
        List<DevicePcbVersionInfo> list = devicePcbVersionInfoService.getPageList(getDevicePcbVersionInfoDO);
        if (list != null && list.size() > 0) {
            voList = EntityConversionUtil.copyList(list, GetVersionListVO.class);
        }
        PageInfo<DevicePcbVersionInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetVersionListVO>> build = PageResult.<List<GetVersionListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-新增和修改版本信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增和修改版本信息")
    @PostMapping("/saveVersionInfo")
    public Result<Objects> saveVersionInfo(@RequestBody @Valid SaveVersionInfoDTO dto) {
        if (dto.getId() != null && dto.getId() != 0) {
            DevicePcbVersionInfo info = devicePcbVersionInfoService.getById(dto.getId());
            if (info == null) {
                return Result.fail("9999", "版本不存在");
            }
            info.setFilePath(dto.getFilePath());
            info.setDtus(dto.getDtus());
            info.setNewVersion(dto.getNewVersion());
            info.setOldVersion(dto.getOldVersion());
            info.setContent(dto.getContent());
            devicePcbVersionInfoService.update(info);
        } else {
            DevicePcbVersionInfo info = new DevicePcbVersionInfo();
            info.setFilePath(dto.getFilePath());
            info.setDtus(dto.getDtus());
            info.setNewVersion(dto.getNewVersion());
            info.setOldVersion(dto.getOldVersion());
            info.setContent(dto.getContent());
            devicePcbVersionInfoService.save(info);
        }
        return Result.suc();
    }


    @Log(title = "PCB终端管理-修改设备号", businessType = BusinessType.INSERT)
    @ApiOperation(value = "修改设备号")
    @PostMapping("/updateDtu")
    public Result<Objects> updateDtu(@RequestBody @Valid UpdateDtuDTO dto) {
        if (dto.getId() == null || dto.getId() == 0) {
            return Result.fail("9999", "设备不存在");
        }
        DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getById(dto.getId());
        if (baseInfo == null) {
            return Result.fail("9999", "设备不存在");
        }
        if (devicePcbBaseInfoService.getByDtu(dto.getNewDtu()) != null) {
            return Result.fail("9999", "该新设备已存在");
        }
        baseInfo.setNewDtu(dto.getNewDtu());
        baseInfo.setChangeSwitch(1);
        devicePcbBaseInfoService.update(baseInfo);
        return Result.suc();
    }

    @Log(title = "PCB终端管理-加载日志", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "加载日志")
    @PostMapping("/uploadLogInfo")
    public Result<Objects> uploadLogInfo(@RequestBody @Valid UploadLogInfoDTO dto) {
        if (dto.getId() == null || dto.getId() == 0) {
            return Result.fail("9999", "设备不存在");
        }
        DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getById(dto.getId());
        if (baseInfo == null) {
            return Result.fail("9999", "设备不存在");
        }
        baseInfo.setUploadLogSwitch(1);
        baseInfo.setUploadLogDay(dto.getDay());
        devicePcbBaseInfoService.update(baseInfo);
        return Result.suc();
    }

    @Log(title = "PCB终端管理-删除版本信息", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除版本信息")
    @PostMapping("/deleteVersionInfo")
    public Result<Objects> saveVersionInfo(@RequestBody @Valid DeleteVersionInfoDTO dto) {
        if (dto.getId() == null || dto.getId() == 0) {
            return Result.fail("9999", "参数有误");
        }
        DevicePcbVersionInfo info = devicePcbVersionInfoService.getById(dto.getId());
        if (info == null) {
            return Result.fail("9999", "版本不存在");
        }
        devicePcbVersionInfoService.delete(dto.getId());
        return Result.suc();
    }

    @Log(title = "PCB终端管理-设置发送数据模式", businessType = BusinessType.DELETE)
    @ApiOperation(value = "设置发送数据模式")
    @PostMapping("/updateSetNetMode")
    public Result<Objects> updateSetNetMode(@RequestBody @Valid UpdateSetNetModeDTO dto) {
        if (StringUtils.isBlank(dto.getDtu())) {
            return Result.fail("9999", "设备号为空");
        }
        DevicePcbBaseInfo info = devicePcbBaseInfoService.getByDtu(dto.getDtu());
        if (info == null) {
            return Result.fail("9999", "设备不存在");
        }
        info.setSetNetMode(dto.getSetNetMode());
        info.setSetNetModeSwitch(1);
        info.setSetNetModeStatus(1);
        devicePcbBaseInfoService.update(info);
        return Result.suc();
    }

    @Log(title = "PCB终端管理-提交拍照", businessType = BusinessType.DELETE)
    @ApiOperation(value = "提交拍照")
    @PostMapping("/submitPhoto")
    public Result<SubmitPhotoVO> submitPhoto(@RequestBody @Valid SubmitPhotoDTO dto) {
        SubmitPhotoVO vo = new SubmitPhotoVO();
        String shortDtu = "";
        String dtu = dto.getDtu();
        if (dtu.length() == 10 || dtu.length() == 16) {
            shortDtu = "Y-" + dtu.substring(dtu.length() - 5, dtu.length());
        } else if (dtu.length() == 11) {
            shortDtu = "Y=" + dtu.substring(dtu.length() - 5, dtu.length());
        }
        DevicePcbBaseInfo info = devicePcbBaseInfoService.getByShortDtu(shortDtu);
        if (info == null) {
            return Result.fail("9999", "设备不存在");
        }
        info.setGetCamStatus(1);
        info.setGetCamSwitch(1);
        devicePcbBaseInfoService.update(info);
        vo.setCurDate(new Date());
        return Result.suc(vo);
    }


    @Log(title = "PCB终端管理- 设备维修", businessType = BusinessType.INSERT)
    @ApiOperation(value = "设备维修")
    @PostMapping("/saveRepairInfo")
    public Result<List<SaveRepairInfoVO>> saveRepairInfo(@RequestBody @Valid SaveRepairInfoDTO dto) {
        List<SaveRepairInfoVO> voList = new ArrayList<>();
        if (StringUtils.isBlank(dto.getPwd()) || !"Zhihuipcb123".equals(dto.getPwd())) {
            return Result.fail("9999", "密码不正确");
        }
        DevicePcbRepairRecordInfo recordInfo = EntityConversionUtil.copy(dto, DevicePcbRepairRecordInfo.class);
        System.out.println("===========imei :" + recordInfo.getImei());
        List<DevicePcbBaseInfo> baseList = devicePcbRepairRecordInfoService.saveRepairInfo(recordInfo);
        if (baseList != null && baseList.size() > 0) {
            voList = EntityConversionUtil.copyList(baseList, SaveRepairInfoVO.class);
        }
        return Result.suc(voList);
    }

    @Log(title = "PCB终端管理- 设备传感器调零", businessType = BusinessType.INSERT)
    @ApiOperation(value = "设备传感器调零")
    @PostMapping("/submitSensorZero")
    public Result<Objects> submitSensorZero(@RequestBody @Valid SubmitSensorZeroDTO dto) {
        DevicePcbSensorInfo info = devicePcbSensorInfoService.getById(dto.getSensorId());
        if (info == null) {
            return Result.fail("9999", "传感器不存在");
        }
        info.setFitZeroSwitch(1);
        info.setFitZeroStatus(1);
        int num = devicePcbSensorInfoService.update(info);
        if (num > 0) {
            return Result.suc();
        }
        return Result.fail("9999", "调零失败");
    }


    @Log(title = "PCB终端管理-出厂批次信息", businessType = BusinessType.SELECT)
    @ApiOperation(value = "出厂批次信息")
    @PostMapping("/getBatchList")
    public Result<PageResult<List<GetBatchListVO>>> getBatchList(@RequestBody @Valid GetBatchListDTO dto) {
        List<GetBatchListVO> voList = new ArrayList<>();
        GetDevicePcbExFactoryBatchInfoDO getDevicePcbExFactoryBatchInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbExFactoryBatchInfoDO.class);
        getDevicePcbExFactoryBatchInfoDO.setSortRow("createTime");
        List<DevicePcbExFactoryBatchInfo> batchList = devicePcbExFactoryBatchInfoService.getPageList(getDevicePcbExFactoryBatchInfoDO);
        if (batchList != null && batchList.size() > 0) {
            List<Long> domainIdList = new ArrayList<>();
            List<Long> modelIdList = new ArrayList<>();
            for (DevicePcbExFactoryBatchInfo info : batchList) {
                if (info.getDomainId() != null && info.getDomainId() != 0) domainIdList.add(info.getDomainId());
                if (info.getModelId() != null && info.getModelId() != 0) modelIdList.add(info.getModelId());
            }
            Map<Long, SystemDomainInfo> domainMap = new HashMap<>();
            if (domainIdList.size() > 0) {
                GetSystemDomainInfoDO getSystemDomainInfoDO = new GetSystemDomainInfoDO();
                getSystemDomainInfoDO.setIdList(domainIdList);
                getSystemDomainInfoDO.setSortRow("createTime");
                List<SystemDomainInfo> domainList = systemDomainInfoService.getAllList(getSystemDomainInfoDO);
                if (domainList != null && domainList.size() > 0) {
                    domainMap = domainList.stream().collect(Collectors.toMap(SystemDomainInfo::getId, Function.identity()));
                }
            }
            Map<Long, SystemDeviceModelInfo> modelMap = new HashMap<>();
            if (modelIdList.size() > 0) {
                GetSystemDeviceModelInfoDO getSystemDeviceModelInfoDO = new GetSystemDeviceModelInfoDO();
                getSystemDeviceModelInfoDO.setSortRow("createTime");
                getSystemDeviceModelInfoDO.setIdList(modelIdList);
                List<SystemDeviceModelInfo> modelList = systemDeviceModelInfoService.getPageList(getSystemDeviceModelInfoDO);
                if (modelList != null && modelList.size() > 0) {
                    modelMap = modelList.stream().collect(Collectors.toMap(SystemDeviceModelInfo::getId, Function.identity()));
                }
            }
            for (DevicePcbExFactoryBatchInfo item : batchList) {
                GetBatchListVO vo = EntityConversionUtil.copy(item, GetBatchListVO.class);
                vo.setDeviceNum(devicePcbBaseInfoService.countByBatchId(item.getBatchId()));
                long factoryId = 0;
                String factoryName = "智慧农林";
                if (item.getFactoryUserId() != null && item.getFactoryUserId() > 0) {
                    factoryId = item.getFactoryUserId();
                    factoryName = item.getFactoryName();
                }
                vo.setFactoryId(factoryId);
                vo.setFactoryName(factoryName);
                if (item.getDomainId() != null && item.getDomainId() != 0 && !domainMap.isEmpty() && domainMap.get(item.getDomainId()) != null) {
                    vo.setDomainId(item.getDomainId());
                    SystemDomainInfo domainInfo = domainMap.get(item.getDomainId());
                    vo.setDomainInfo(domainInfo.getDomain() + ":" + domainInfo.getPort());
                }

                if (item.getModelId() != null && item.getModelId() != 0 && !modelMap.isEmpty() && modelMap.get(item.getModelId()) != null) {
                    vo.setModelId(item.getModelId());
                    vo.setModelName(modelMap.get(item.getModelId()).getName());
                }
                voList.add(vo);
            }
        }
        PageInfo<DevicePcbExFactoryBatchInfo> pageInfo = new PageInfo<>(batchList);
        PageResult<List<GetBatchListVO>> build = PageResult.<List<GetBatchListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "PCB终端管理-新增修改出厂批次信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增修改出厂批次信息")
    @PostMapping("/saveBatchInfo")
    public Result<Objects> saveBatchInfo(@RequestBody @Valid SaveBatchInfoDTO dto) {
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            DevicePcbExFactoryBatchInfo batchInfo = EntityConversionUtil.copy(dto, DevicePcbExFactoryBatchInfo.class);
            if (batchInfo.getServiceYear() == null || batchInfo.getServiceYear() == 0) batchInfo.setServiceYear(2);
            batchInfo.setFactoryUserId(dto.getFactoryId());
            batchInfo.setFactoryName(dto.getFactory());
            batchInfo.setExFactory(0);
            batchInfo.setModelId(dto.getModelId());
            batchInfo.setDomainId(dto.getDomainId());
            devicePcbExFactoryBatchInfoService.save(batchInfo);
            return Result.suc();
        } else {
            DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(dto.getBatchId());
            if (batchInfo == null) {
                return Result.fail("9999", "批次不存在");
            }
            if (batchInfo.getExFactory() == 1) {
                return Result.fail("9999", "该批次已经出厂，不能修改");
            }
            batchInfo = EntityConversionUtil.copy(dto, DevicePcbExFactoryBatchInfo.class);
            if (batchInfo.getServiceYear() == null || batchInfo.getServiceYear() == 0) batchInfo.setServiceYear(2);
            batchInfo.setFactoryUserId(dto.getFactoryId());
            batchInfo.setFactoryName(dto.getFactory());
            batchInfo.setModelId(dto.getModelId());
            batchInfo.setDomainId(dto.getDomainId());
            devicePcbExFactoryBatchInfoService.update(batchInfo);
            return Result.suc();
        }
    }

    @Log(title = "PCB终端管理-设备批次提交出库", businessType = BusinessType.INSERT)
    @ApiOperation(value = "设备批次提交出库")
    @PostMapping("/submitExFactory")
    public Result<Objects> submitExFactory(@RequestBody @Valid SubmitExFactoryDTO dto) {
        DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            return Result.fail("9999", "批次不存在");
        }
        if (batchInfo.getExFactory() == 1) {
            return Result.fail("9999", "该批次已经出库，不能重复出库");
        }
        batchInfo.setExFactory(1);
        batchInfo.setExDate(new Date());
        int num = devicePcbExFactoryBatchInfoService.updateExFactory(batchInfo);
        if (num == 0) return Result.fail("9999", "出库失败");
        return Result.suc();
    }

    @Log(title = "PCB终端管理-统计当月服务卡到期设备信息", businessType = BusinessType.DELETE)
    @ApiOperation(value = "统计当月服务卡到期设备信息")
    @PostMapping("/statisticsSimExpireInfo")
    public Result<StatisticsSimExpireInfoVO> statisticsSimExpireInfo(@RequestBody @Valid StatisticsSimExpireInfoDTO dto) {
        StatisticsSimExpireInfoVO vo = new StatisticsSimExpireInfoVO();
        List<GetDeviceListVO> voList = new ArrayList<>();
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbBaseInfoDO.class);
        Date d = DateUtils.parseStrToDate(dto.getMonth(), DateUtils.DATE_FORMAT_YYYY_MM);
        int year = Integer.valueOf(DateUtils.getYear(d));
        int month = Integer.parseInt(DateUtils.getMonth(d));
        Date firstDate = DateUtils.getFirstDayOfMonth(year, month);
        Date lastDate = DateUtils.getLastDayOfMonth(year, month);
        getDevicePcbBaseInfoDO.setServiceStartTime(firstDate);
        getDevicePcbBaseInfoDO.setServiceEndTime(lastDate);
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        getDevicePcbBaseInfoDO.setSortOrder("desc");
        List<DevicePcbBaseInfo> deviceList = devicePcbBaseInfoService.selectSimExpireList(getDevicePcbBaseInfoDO);
        if (deviceList != null && deviceList.size() > 0) {
            deviceList.forEach(item -> {
                GetDeviceListVO deviceVo = EntityConversionUtil.copy(item, GetDeviceListVO.class);
                deviceVo.setDeviceId(item.getId());
                voList.add(deviceVo);
            });
        }
        vo.setDeviceList(voList);
        PageInfo<DevicePcbBaseInfo> pageInfo = new PageInfo<>(deviceList);
        PageResult<List<GetDeviceListVO>> build = PageResult.<List<GetDeviceListVO>>builder().result(voList).pageInfo(pageInfo).build();
        vo.setTotal(build.getTotal() + "");
        return Result.suc(vo);
    }


    @Log(title = "PCB终端管理-安卓版SIM记录信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "安卓版SIM记录信息")
    @PostMapping("/getDeviceSimRecordList")
    public Result<PageResult<List<GetDeviceSimRecordListVO>>> getDeviceSimRecordList(@RequestBody @Valid GetDeviceSimRecordListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceSimRecordListVO> voList = new ArrayList<>();
        GetDevicePcbSimRecordInfoDO getDevicePcbSimRecordInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbSimRecordInfoDO.class);
        List<DevicePcbSimRecordInfo> list = devicePcbSimRecordInfoService.getPageList(getDevicePcbSimRecordInfoDO);
        if (list != null && list.size() > 0) {
            voList = EntityConversionUtil.copyList(list, GetDeviceSimRecordListVO.class);
        }
        PageInfo<DevicePcbSimRecordInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetDeviceSimRecordListVO>> build = PageResult.<List<GetDeviceSimRecordListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }


    @Log(title = "PCB终端管理-安卓版出厂设备号池记录列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "安卓版出厂设备号池记录列表")
    @PostMapping("/getDeviceDtuPoolList")
    public Result<PageResult<List<GetDeviceDtuPoolListVO>>> getDeviceDtuPoolList(@RequestBody @Valid GetDeviceDtuPoolListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceDtuPoolListVO> voList = new ArrayList<>();
        GetDevicePcbExFactoryDtuPoolInfoDO getDevicePcbExFactoryDtuPoolInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbExFactoryDtuPoolInfoDO.class);
        List<DevicePcbExFactoryDtuPoolInfo> list = devicePcbExFactoryDtuPoolInfoService.getPageList(getDevicePcbExFactoryDtuPoolInfoDO);
        if (list != null && list.size() > 0) {
            voList = EntityConversionUtil.copyList(list, GetDeviceDtuPoolListVO.class);
        }
        PageInfo<DevicePcbExFactoryDtuPoolInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetDeviceDtuPoolListVO>> build = PageResult.<List<GetDeviceDtuPoolListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-安卓版出厂SIM卡号池记录列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "安卓版出厂SIM卡号池记录列表")
    @PostMapping("/getDeviceSimPoolList")
    public Result<PageResult<List<GetDeviceSimPoolListVO>>> getDeviceSimPoolList(@RequestBody @Valid GetDeviceSimPoolListDTO dto) {
        LoginUserDetails loginUserDetails = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUserDetails.getUser();
        List<GetDeviceSimPoolListVO> voList = new ArrayList<>();
        GetDevicePcbExFactorySimPoolInfoDO getDevicePcbExFactorySimPoolInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbExFactorySimPoolInfoDO.class);
        List<DevicePcbExFactorySimPoolInfo> list = devicePcbExFactorySimPoolInfoService.getPageList(getDevicePcbExFactorySimPoolInfoDO);
        if (list != null && list.size() > 0) {
            List<Long> modelIdList = new ArrayList<>();
            for (DevicePcbExFactorySimPoolInfo info : list) {
                if (info.getModelId() != null && info.getModelId() != 0) modelIdList.add(info.getModelId());
            }
            Map<Long, SystemDeviceModelInfo> modelMap = new HashMap<>();
            if (modelIdList.size() > 0) {
                GetSystemDeviceModelInfoDO getSystemDeviceModelInfoDO = new GetSystemDeviceModelInfoDO();
                getSystemDeviceModelInfoDO.setSortRow("createTime");
                getSystemDeviceModelInfoDO.setIdList(modelIdList);
                List<SystemDeviceModelInfo> modelList = systemDeviceModelInfoService.getPageList(getSystemDeviceModelInfoDO);
                if (modelList != null && modelList.size() > 0) {
                    modelMap = modelList.stream().collect(Collectors.toMap(SystemDeviceModelInfo::getId, Function.identity()));
                }
            }
            for (DevicePcbExFactorySimPoolInfo info : list) {
                GetDeviceSimPoolListVO vo = EntityConversionUtil.copy(info, GetDeviceSimPoolListVO.class);
                if (!modelMap.isEmpty() && info.getModelId() != null && info.getModelId() > 0 && modelMap.get(info.getModelId()) != null)
                    vo.setModelName(modelMap.get(info.getModelId()).getName());
                voList.add(vo);
            }
        }
        PageInfo<DevicePcbExFactorySimPoolInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetDeviceSimPoolListVO>> build = PageResult.<List<GetDeviceSimPoolListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-保存设备号到池中", businessType = BusinessType.INSERT)
    @ApiOperation(value = "保存设备号到池中")
    @PostMapping("/saveDtuToPool")
    public Result<Objects> saveDtuToPool(@RequestBody @Valid SaveDtuToPoolDTO dto) {
        List<List<Object>> list = FileUtils.getExcelListByFileUrl(dto.getFileUrl());
        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("9999", "文件为空");
        }
        List<DevicePcbExFactoryDtuPoolInfo> poolList = new ArrayList<>();
        for (int i = 1; i < list.size(); i++) {
            List<Object> oList = list.get(i);
            String dtu = oList.get(0).toString();
            if (devicePcbExFactoryDtuPoolInfoService.getByDtu(dtu) != null) continue;
            String shortDtu = oList.get(1).toString();
            String qrContent = oList.get(2).toString();
            DevicePcbExFactoryDtuPoolInfo poolInfo = new DevicePcbExFactoryDtuPoolInfo();
            poolInfo.setDtu(dtu);
            poolInfo.setShortDtu(shortDtu);
            poolInfo.setQrContent(qrContent);
            poolInfo.setStatus(0);
            poolInfo.setCreatedTime(new Date());
            poolList.add(poolInfo);
        }
        if (poolList.size() > 0)
            devicePcbExFactoryDtuPoolInfoService.saveList(poolList);
        return Result.suc();
    }

    @Log(title = "PCB终端管理-保存SIM卡号到池中", businessType = BusinessType.INSERT)
    @ApiOperation(value = "保存SIM卡号到池中")
    @PostMapping("/saveSimToPool")
    public Result<Objects> saveSimToPool(@RequestBody @Valid SaveSimToPoolDTO dto) {
        List<List<Object>> list = FileUtils.getExcelListByFileUrl(dto.getFileUrl());
        if (CollectionUtils.isEmpty(list)) {
            return Result.fail("9999", "文件为空");
        }
        List<DevicePcbExFactorySimPoolInfo> poolList = new ArrayList<>();
        for (int i = 1; i < list.size(); i++) {
            List<Object> oList = list.get(i);
            String sim = oList.get(0).toString();
            if (devicePcbExFactorySimPoolInfoService.getBySim(sim) != null) continue;
            DevicePcbExFactorySimPoolInfo poolInfo = new DevicePcbExFactorySimPoolInfo();
            poolInfo.setSim(sim);
            poolInfo.setStatus(0);
            poolInfo.setCreatedTime(new Date());
            poolList.add(poolInfo);
        }
        if (poolList.size() > 0)
            devicePcbExFactorySimPoolInfoService.saveList(poolList);
        return Result.suc();
    }

    @Log(title = "PCB终端管理-查询每月SIM卡到期列表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "查询每月SIM卡到期列表")
    @PostMapping("/getExpireSimListInPool")
    public Result<PageResult<List<GetDeviceSimPoolListVO>>> getExpireSimListInPool(@RequestBody @Valid GetExpireSimListInPoolDTO dto) {
        List<GetDeviceSimPoolListVO> voList = new ArrayList<>();
        GetDevicePcbExFactorySimPoolInfoDO getDevicePcbExFactorySimPoolInfoDO = EntityConversionUtil.copy(dto, GetDevicePcbExFactorySimPoolInfoDO.class);
        String start = DateUtils.parseDateToStr(new Date(), DateUtils.DATE_FORMAT_YYYY_MM_DD) + "00:00:00";
        Date serviceStartTime = DateUtils.parseStrToDate(start, DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        Date serviceEndTime = DateUtils.addDate(serviceStartTime, 0, 0, 31, 0, 0, 0, 0);
        getDevicePcbExFactorySimPoolInfoDO.setServiceStartTime(serviceStartTime);
        getDevicePcbExFactorySimPoolInfoDO.setServiceEndTime(serviceEndTime);
        getDevicePcbExFactorySimPoolInfoDO.setSortRow("serviceEndTime");
        getDevicePcbExFactorySimPoolInfoDO.setSortOrder("asc");
        List<DevicePcbExFactorySimPoolInfo> list = devicePcbExFactorySimPoolInfoService.getPageList(getDevicePcbExFactorySimPoolInfoDO);
        if (list != null && list.size() > 0) {
            List<Long> modelIdList = new ArrayList<>();
            for (DevicePcbExFactorySimPoolInfo info : list) {
                if (info.getModelId() != null && info.getModelId() != 0) modelIdList.add(info.getModelId());
            }
            Map<Long, SystemDeviceModelInfo> modelMap = new HashMap<>();
            if (modelIdList.size() > 0) {
                GetSystemDeviceModelInfoDO getSystemDeviceModelInfoDO = new GetSystemDeviceModelInfoDO();
                getSystemDeviceModelInfoDO.setSortRow("createTime");
                getSystemDeviceModelInfoDO.setIdList(modelIdList);
                List<SystemDeviceModelInfo> modelList = systemDeviceModelInfoService.getPageList(getSystemDeviceModelInfoDO);
                if (modelList != null && modelList.size() > 0) {
                    modelMap = modelList.stream().collect(Collectors.toMap(SystemDeviceModelInfo::getId, Function.identity()));
                }
            }
            for (DevicePcbExFactorySimPoolInfo info : list) {
                GetDeviceSimPoolListVO vo = EntityConversionUtil.copy(info, GetDeviceSimPoolListVO.class);
                if (!modelMap.isEmpty() && info.getModelId() != null && info.getModelId() > 0 && modelMap.get(info.getModelId()) != null)
                    vo.setModelName(modelMap.get(info.getModelId()).getName());
                voList.add(vo);
            }
        }
        PageInfo<DevicePcbExFactorySimPoolInfo> pageInfo = new PageInfo<>(list);
        PageResult<List<GetDeviceSimPoolListVO>> build = PageResult.<List<GetDeviceSimPoolListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "PCB终端管理-修改设备号池中的出厂状态", businessType = BusinessType.INSERT)
    @ApiOperation(value = "修改设备号池中的出厂状态")
    @PostMapping("/updateStatusInDtuPool")
    public Result<Objects> updateStatusInDtuPool(@RequestParam("file") MultipartFile excelFile1) {
        String dtus1 = "";
        List<UpdateStatusInDtuPoolDTO> excelList1 = ExcelUtil.readExcel(excelFile1, 1, 1, UpdateStatusInDtuPoolDTO.class);
        if (StringUtils.isNull(excelList1) || excelList1.size() <= 0) {
            throw new BusinessException(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }
        List<SaveSimToPoolErrorVO> errorVoList = new ArrayList<>();

        List<DevicePcbExFactorySimPoolInfo> simList = new ArrayList<>();
        List<DevicePcbExFactoryDtuPoolInfo> dtuList = new ArrayList<>();
        System.out.println("excel总数：" + excelList1.size());
        excelList1 = excelList1.stream().filter(o -> {
            String qrContent = o.getQrContent();
            if ("".equals(qrContent) || qrContent.length() < 16) {
                errorVoList.add(EntityConversionUtil.copy(o, SaveSimToPoolErrorVO.class).errMsg("字段" + qrContent + "有误"));
                log.error("字段{}有误", qrContent);
                return false;
            }
            String[] str = new String[16];
            for (int i = 0; i < qrContent.length(); i++) {
                String s = qrContent.substring(i, i + 1);
                str[i] = s;
            }
            String dtu = str[3] + str[4] + str[5] + str[7] + str[8] + str[11] + str[12] + str[13] + str[14] + str[15];
            DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getByDtu(dtu);
            if (baseInfo == null) {
                errorVoList.add(EntityConversionUtil.copy(o, SaveSimToPoolErrorVO.class).errMsg("设备" + qrContent + "不存在"));
                log.error("设备{}已经录入", qrContent);
                return false;
            }
            DevicePcbExFactoryDtuPoolInfo dtuPool = devicePcbExFactoryDtuPoolInfoService.getByDtu(dtu);
            if (dtuPool == null) {
                errorVoList.add(EntityConversionUtil.copy(o, SaveSimToPoolErrorVO.class).errMsg("设备号" + qrContent + "未在号码池中"));
                log.error("设备{}未在号码池中", qrContent);
                return false;
            }
            DevicePcbExFactorySimPoolInfo simPool = devicePcbExFactorySimPoolInfoService.getBySim(baseInfo.getSim());
            if (simPool == null) {
                errorVoList.add(EntityConversionUtil.copy(o, SaveSimToPoolErrorVO.class).errMsg("该设备对应的SIM号" + qrContent + "未在号码池中"));
                log.error("该设备对应的SIM号{}未在号码池中", qrContent);
                return false;
            }
            dtuPool.setStatus(0);
            dtuPool.setLastModifiedTime(new Date());
            simPool.setStatus(0);
            simPool.setLastModifiedTime(new Date());
            dtuList.add(dtuPool);
            simList.add(simPool);
            return true;
        }).collect(Collectors.toList());

        if (dtuList.size() > 0) {
            devicePcbExFactoryDtuPoolInfoService.updateList(dtuList);
        }
        if (simList.size() > 0) {
            devicePcbExFactorySimPoolInfoService.updateList(simList);
        }
        return Result.suc();
    }

    @Log(title = "PCB终端管理 - 按批次导出设备信息", businessType = BusinessType.EXPORT, isSaveResponseData = false)
    @ApiOperation(value = "按批次导出设备信息")
    @PostMapping(value = "/exportDeviceListByBatch")
    public void exportDeviceListByBatch(@RequestBody @Valid ExportDeviceListByBatchDTO dto, HttpServletResponse response) throws BusinessException {
        List<ExportDeviceListByBatchVO> voList = new ArrayList<>();
        DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) return;
        String factoryName = batchInfo.getFactoryName();
        String model = "";
        if (batchInfo.getModelId() != null && batchInfo.getModelId() != 0) {
            SystemDeviceModelInfo modelInfo = systemDeviceModelInfoService.getById(batchInfo.getModelId());
            if (modelInfo != null) model = modelInfo.getName();
        }
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
        getDevicePcbBaseInfoDO.setBatchId(dto.getBatchId());
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            System.out.println("====baseList :" + baseList.size());
            for (DevicePcbBaseInfo item : baseList) {
                ExportDeviceListByBatchVO vo = new ExportDeviceListByBatchVO();
                vo.setDtuType("4G");//终端类型
                String dtu = item.getDtu();
                vo.setDtu(dtu);//终端编号
                vo.setModel(model);//终端型号
                vo.setCommu("");//通信协议
                vo.setSim(item.getSim());//sim卡号
                String exDate = "";
                if (batchInfo.getExDate() != null) {
                    exDate = DateUtils.parseDateToStr(batchInfo.getExDate(), DateUtils.DATE_FORMAT_YYYY_MM_DD);
                }
                vo.setExDate(exDate);
                vo.setServiceYear(batchInfo.getServiceYear());
                if ("沃得".equals(factoryName)) {
                    vo.setFactory("CAAMS");//生产厂家
                }
                vo.setRemark("");//备注
                vo.setImei(item.getImei());//IMEI号
                voList.add(vo);
            }
        }
        String fileName = "pcb_device_list_" + DateUtils.parseDateToStr(DateUtils.YYYYMMDD_HHMM, new Date());
        try {
            System.out.println("====voList :" + voList.size());
            ExcelUtil.writeExcel(response, voList, fileName, "OBD设备信息", new ExportDeviceListByBatchVO());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出失败，文件名:{}", fileName);
        }
    }

    @Log(title = "PCB终端管理-验证纸箱号是否能用", businessType = BusinessType.SELECT)
    @ApiOperation(value = "验证纸箱号是否能用")
    @PostMapping("/checkCartonNo")
    public Result<Objects> checkCartonNo(@RequestBody @Valid CheckCartonNoDTO dto) {
        if (StringUtils.isBlank(dto.getCartonNo())) {
            return Result.fail("9999", "纸箱号为空");
        }
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
        getDevicePcbBaseInfoDO.setCartonNo(dto.getCartonNo());
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            return Result.fail("9999", "该纸箱号已经使用过");
        }
        return Result.suc();
    }

    @Log(title = "PCB终端管理-设备出库前扫描", businessType = BusinessType.SELECT)
    @ApiOperation(value = "设备出库前扫描")
    @PostMapping("/scanBeforeExFactory")
    public Result<ScanBeforeExFactoryVO> scanBeforeExFactory(@RequestBody @Valid ScanBeforeExFactoryDTO dto) {
        ScanBeforeExFactoryVO vo = new ScanBeforeExFactoryVO();
        String dtu = "";
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            vo.setStatus(0);
            vo.setMsg("没有批次");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            vo.setStatus(0);
            vo.setMsg("批次不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (batchInfo.getExFactory() == 1) {
            vo.setStatus(0);
            vo.setMsg("该批次已出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (StringUtils.isBlank(dto.getSdtu())) {
            vo.setStatus(0);
            vo.setMsg("设备号不能为空");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        String sdtu = dto.getSdtu();
        DevicePcbBaseInfo baseInfo = null;
        if (sdtu.startsWith("86")) {
            List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getByImei(dto.getSdtu());
            if (baseList != null && baseList.size() > 0) {
                if (baseList.size() == 1) {
                    baseInfo = baseList.get(0);
                    dtu = baseInfo.getDtu();
                } else if (baseList.size() > 1) {
                    vo.setStatus(0);
                    vo.setMsg("IMEI有重复设备");
                    return Result.suc(vo);
                }
            }
        } else {//北京的设备
            if (sdtu.length() > 15) {
                String[] str = new String[16];
                for (int i = 0; i < dto.getSdtu().length(); i++) {
                    String s = dto.getSdtu().substring(i, i + 1);
                    str[i] = s;
                }
                dtu = str[3] + str[4] + str[5] + str[7] + str[8] + str[11] + str[12] + str[13] + str[14] + str[15];
                baseInfo = devicePcbBaseInfoService.getByDtu(dtu);
            }
        }
        if (baseInfo == null) {
            vo.setStatus(0);
            vo.setMsg("设备不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DevicePcbExFactoryDtuPoolInfo dtuPool = devicePcbExFactoryDtuPoolInfoService.getByDtu(dtu);
        if (dtuPool == null) {
            vo.setStatus(0);
            vo.setMsg("该设备不允许出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (dtuPool.getStatus() == 1) {
            vo.setStatus(0);
            vo.setMsg("该设备已经出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DevicePcbExFactorySimPoolInfo simPool = devicePcbExFactorySimPoolInfoService.getBySim(baseInfo.getSim());
        if (simPool == null) {
            vo.setStatus(0);
            vo.setMsg("该设备的SIM卡号不允许出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (simPool.getStatus() == 1) {
            vo.setStatus(0);
            vo.setMsg("该设备的SIM卡号已经出厂过");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (StringUtils.isNotBlank(dto.getVersion())) {
            if (!baseInfo.getCurVersion().equals(dto.getVersion())) {
                vo.setStatus(0);
                vo.setMsg("该设备未升级");
                vo.setSdtu(dto.getSdtu());
                vo.setDtus(dto.getDtus());
                vo.setRepeats(dto.getRepeats());
                return Result.suc(vo);
            }
        }

        if (baseInfo.getBatchId() != null && baseInfo.getBatchId() != 0) {
            vo.setStatus(0);
            vo.setMsg("该设备已出库");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
        getDevicePcbBaseInfoDO.setImei(baseInfo.getImei());
        getDevicePcbBaseInfoDO.setSim(baseInfo.getSim());
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
        if (baseList.size() > 1) {
            vo.setStatus(0);
            vo.setMsg("IMEI和SIM有重复");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        String dtus = dto.getDtus();
        String repeats = dto.getRepeats();
        int status = 1;
        String msg = "合格";
        if (StringUtils.isBlank(dtus)) {
            dtus = dtu;
        } else {
            if (dtus.indexOf(dtu) != -1) {//有重复设备
                status = 0;
                msg = "有重复设备";
                if (StringUtils.isBlank(repeats)) {
                    repeats = dtu;
                } else {
                    if (repeats.indexOf(dtu) == -1) repeats = repeats + ";" + dtu;
                }
            } else {
                dtus = dtus + ";" + dtu;
            }
        }
        ScanBeforeExFactoryDeviceVO deviceInfo = EntityConversionUtil.copy(baseInfo, ScanBeforeExFactoryDeviceVO.class);
        if (baseInfo.getOnLineStatus() == 0) {//离线
            deviceInfo.setBlackout(1);
        } else deviceInfo.setBlackout(0);
        deviceInfo.setSdtu(dto.getSdtu());
        vo.setStatus(status);
        vo.setMsg(msg);
        vo.setSdtu(dto.getSdtu());
        vo.setRepeats(repeats);
        vo.setDtus(dtus);
        vo.setDeviceInfo(deviceInfo);
        return Result.suc(vo);
    }


    @Log(title = "PCB终端管理-北京08设备出库前扫描", businessType = BusinessType.SELECT)
    @ApiOperation(value = "北京08设备出库前扫描")
    @PostMapping("/scanBeforeExFactoryOfBj")
    public Result<ScanBeforeExFactoryVO> scanBeforeExFactoryOfBj(@RequestBody @Valid ScanBeforeExFactoryDTO dto) {
        ScanBeforeExFactoryVO vo = new ScanBeforeExFactoryVO();
        String dtu = "";
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            vo.setStatus(0);
            vo.setMsg("没有批次");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            vo.setStatus(0);
            vo.setMsg("批次不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (batchInfo.getExFactory() == 1) {
            vo.setStatus(0);
            vo.setMsg("该批次已出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (StringUtils.isBlank(dto.getSdtu())) {
            vo.setStatus(0);
            vo.setMsg("设备号不能为空");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        String sdtu = dto.getSdtu();
        DevicePcbBjBaseInfo baseInfo = null;
        if (sdtu.length() > 15) {
            String[] str = new String[16];
            for (int i = 0; i < dto.getSdtu().length(); i++) {
                String s = dto.getSdtu().substring(i, i + 1);
                str[i] = s;
            }
            dtu = str[3] + str[4] + str[5] + str[7] + str[8] + str[11] + str[12] + str[13] + str[14] + str[15];
            baseInfo = devicePcbBjBaseInfoService.getByDtu(dtu);
        }
        if (baseInfo == null) {
            vo.setStatus(0);
            vo.setMsg("设备不存在");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DevicePcbExFactoryDtuPoolInfo dtuPool = devicePcbExFactoryDtuPoolInfoService.getByDtu(dtu);
        if (dtuPool == null) {
            vo.setStatus(0);
            vo.setMsg("该设备不允许出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (dtuPool.getStatus() == 1) {
            vo.setStatus(0);
            vo.setMsg("该设备已经出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        DevicePcbExFactorySimPoolInfo simPool = devicePcbExFactorySimPoolInfoService.getBySim(baseInfo.getSim());
        if (simPool == null) {
            vo.setStatus(0);
            vo.setMsg("该设备的SIM卡号不允许出厂");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        if (simPool.getStatus() == 1) {
            vo.setStatus(0);
            vo.setMsg("该设备的SIM卡号已经出厂过");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        /*if (StringUtils.isNotBlank(dto.getVersion())) {
            if (!baseInfo.getCurVersion().equals(dto.getVersion())) {
                vo.setStatus(0);
                vo.setMsg("该设备未升级");
                vo.setSdtu(dto.getSdtu());
                vo.setDtus(dto.getDtus());
                vo.setRepeats(dto.getRepeats());
                return Result.suc(vo);
            }
        }*/

        if (baseInfo.getBatchId() != null && baseInfo.getBatchId() != 0) {
            vo.setStatus(0);
            vo.setMsg("该设备已出库");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }
        /*GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
        getDevicePcbBaseInfoDO.setImei(baseInfo.getImei());
        getDevicePcbBaseInfoDO.setSim(baseInfo.getSim());
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
        if (baseList.size() > 1) {
            vo.setStatus(0);
            vo.setMsg("IMEI和SIM有重复");
            vo.setSdtu(dto.getSdtu());
            vo.setDtus(dto.getDtus());
            vo.setRepeats(dto.getRepeats());
            return Result.suc(vo);
        }*/
        String dtus = dto.getDtus();
        String repeats = dto.getRepeats();
        int status = 1;
        String msg = "合格";
        if (StringUtils.isBlank(dtus)) {
            dtus = dtu;
        } else {
            if (dtus.indexOf(dtu) != -1) {//有重复设备
                status = 0;
                msg = "有重复设备";
                if (StringUtils.isBlank(repeats)) {
                    repeats = dtu;
                } else {
                    if (repeats.indexOf(dtu) == -1) repeats = repeats + ";" + dtu;
                }
            } else {
                dtus = dtus + ";" + dtu;
            }
        }
        ScanBeforeExFactoryDeviceVO deviceInfo = EntityConversionUtil.copy(baseInfo, ScanBeforeExFactoryDeviceVO.class);
        deviceInfo.setBlackout(1);
        deviceInfo.setSdtu(dto.getSdtu());
        vo.setStatus(status);
        vo.setMsg(msg);
        vo.setSdtu(dto.getSdtu());
        vo.setRepeats(repeats);
        vo.setDtus(dtus);
        vo.setDeviceInfo(deviceInfo);
        return Result.suc(vo);
    }

    @Log(title = "PCB终端管理-扫描设备提交出厂", businessType = BusinessType.INSERT)
    @ApiOperation(value = "扫描设备提交出厂")
    @PostMapping("/submitDeviceExFactory")
    public Result<Objects> submitDeviceExFactory(@RequestBody @Valid SubmitDeviceExFactoryDTO dto) {
        if (StringUtils.isBlank(dto.getDtus())) {
            return Result.fail("9999", "设备号为空");
        }
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            return Result.fail("9999", "批次ID为空");
        }
        if (StringUtils.isBlank(dto.getCartonNo())) {
            return Result.fail("9999", "纸箱号为空");
        }
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
        getDevicePcbBaseInfoDO.setCartonNo(dto.getCartonNo());
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            return Result.fail("9999", "该纸箱号已经用过");
        }
        DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            return Result.fail("9999", "批次不存在");
        }
        String[] dtuStr = dto.getDtus().split(";");
        List<String> dtus = new ArrayList<>();
        List<String> sims = new ArrayList<>();
        List<DevicePcbBaseInfo> updateBaseList = new ArrayList<>();
        for (String dtu : dtuStr) {
            DevicePcbBaseInfo baseInfo = devicePcbBaseInfoService.getByDtu(dtu);
            baseInfo.setBatchId(Long.valueOf(batchInfo.getBatchId()));
            baseInfo.setFactoryUserId(batchInfo.getFactoryUserId());
            baseInfo.setCartonNo(dto.getCartonNo());
            updateBaseList.add(baseInfo);
//            devicePcbBaseInfoService.update(baseInfo);
        }
        //更新号码池的状态
        List<DevicePcbExFactoryDtuPoolInfo> updateDtuPoolList = new ArrayList<>();
        GetDevicePcbExFactoryDtuPoolInfoDO getDevicePcbExFactoryDtuPoolInfoDO = new GetDevicePcbExFactoryDtuPoolInfoDO();
        getDevicePcbExFactoryDtuPoolInfoDO.setDtus(dtus);
        List<DevicePcbExFactoryDtuPoolInfo> dtuPoolList = devicePcbExFactoryDtuPoolInfoService.getAllList(getDevicePcbExFactoryDtuPoolInfoDO);
        if (dtuPoolList.size() > 0) {
            for (DevicePcbExFactoryDtuPoolInfo info : dtuPoolList) {
                info.setStatus(1);//已出厂
                info.setLastModifiedTime(new Date());
                updateDtuPoolList.add(info);
            }
            devicePcbExFactoryDtuPoolInfoService.updateList(updateDtuPoolList);
        }
        devicePcbBaseInfoService.updateList(updateBaseList);

        //更新SIM卡号池中的状态
        List<DevicePcbExFactorySimPoolInfo> updateSimPoolList = new ArrayList<>();
        GetDevicePcbExFactorySimPoolInfoDO getDevicePcbExFactorySimPoolInfoDO = new GetDevicePcbExFactorySimPoolInfoDO();
        getDevicePcbExFactorySimPoolInfoDO.setSims(sims);
        List<DevicePcbExFactorySimPoolInfo> simPoolList = devicePcbExFactorySimPoolInfoService.getAllList(getDevicePcbExFactorySimPoolInfoDO);
        if (simPoolList.size() > 0) {
            for (DevicePcbExFactorySimPoolInfo info : simPoolList) {
                info.setStatus(1);//已出厂
                info.setLastModifiedTime(new Date());
                updateSimPoolList.add(info);
            }
            devicePcbExFactorySimPoolInfoService.updateList(updateSimPoolList);
        }
        DevicePcbExFactoryScanRecordInfo recordInfo = new DevicePcbExFactoryScanRecordInfo();
        recordInfo.setBatchId(batchInfo.getBatchId());
        recordInfo.setCartonNo(dto.getCartonNo());
        recordInfo.setPassDtus(dto.getDtus());
        recordInfo.setNoPassDtus(dto.getNoPassDtus());
        devicePcbExFactoryScanRecordInfoService.save(recordInfo);
        return Result.suc();
    }


    @Log(title = "PCB终端管理-北京08设备扫描设备提交出厂", businessType = BusinessType.INSERT)
    @ApiOperation(value = "北京08设备扫描设备提交出厂")
    @PostMapping("/submitDeviceExFactoryOfBj")
    public Result<Objects> submitDeviceExFactoryOfBj(@RequestBody @Valid SubmitDeviceExFactoryDTO dto) {
        if (StringUtils.isBlank(dto.getDtus())) {
            return Result.fail("9999", "设备号为空");
        }
        if (dto.getBatchId() == null || dto.getBatchId() == 0) {
            return Result.fail("9999", "批次ID为空");
        }
        if (StringUtils.isBlank(dto.getCartonNo())) {
            return Result.fail("9999", "纸箱号为空");
        }
        GetDevicePcbBjBaseInfoDO getDevicePcbBjBaseInfoDO = new GetDevicePcbBjBaseInfoDO();
        getDevicePcbBjBaseInfoDO.setCartonNo(dto.getCartonNo());
        getDevicePcbBjBaseInfoDO.setSortRow("createTime");
        List<DevicePcbBjBaseInfo> baseList = devicePcbBjBaseInfoService.getAllList(getDevicePcbBjBaseInfoDO);
        if (baseList != null && baseList.size() > 0) {
            return Result.fail("9999", "该纸箱号已经用过");
        }
        DevicePcbExFactoryBatchInfo batchInfo = devicePcbExFactoryBatchInfoService.getById(dto.getBatchId());
        if (batchInfo == null) {
            return Result.fail("9999", "批次不存在");
        }
        String[] dtuStr = dto.getDtus().split(";");
        List<String> dtus = new ArrayList<>();
        List<String> sims = new ArrayList<>();
        List<DevicePcbBjBaseInfo> updateBaseList = new ArrayList<>();
        for (String dtu : dtuStr) {
            DevicePcbBjBaseInfo baseInfo = devicePcbBjBaseInfoService.getByDtu(dtu);
            baseInfo.setBatchId(Long.valueOf(batchInfo.getBatchId()));
            baseInfo.setFactoryUserId(batchInfo.getFactoryUserId());
            baseInfo.setCartonNo(dto.getCartonNo());
            updateBaseList.add(baseInfo);
//            devicePcbBaseInfoService.update(baseInfo);
        }
        //更新号码池的状态
        List<DevicePcbExFactoryDtuPoolInfo> updateDtuPoolList = new ArrayList<>();
        GetDevicePcbExFactoryDtuPoolInfoDO getDevicePcbExFactoryDtuPoolInfoDO = new GetDevicePcbExFactoryDtuPoolInfoDO();
        getDevicePcbExFactoryDtuPoolInfoDO.setDtus(dtus);
        List<DevicePcbExFactoryDtuPoolInfo> dtuPoolList = devicePcbExFactoryDtuPoolInfoService.getAllList(getDevicePcbExFactoryDtuPoolInfoDO);
        if (dtuPoolList.size() > 0) {
            for (DevicePcbExFactoryDtuPoolInfo info : dtuPoolList) {
                info.setStatus(1);//已出厂
                info.setLastModifiedTime(new Date());
                updateDtuPoolList.add(info);
            }
            devicePcbExFactoryDtuPoolInfoService.updateList(updateDtuPoolList);
        }
        devicePcbBjBaseInfoService.updateList(updateBaseList);

        //更新SIM卡号池中的状态
        List<DevicePcbExFactorySimPoolInfo> updateSimPoolList = new ArrayList<>();
        GetDevicePcbExFactorySimPoolInfoDO getDevicePcbExFactorySimPoolInfoDO = new GetDevicePcbExFactorySimPoolInfoDO();
        getDevicePcbExFactorySimPoolInfoDO.setSims(sims);
        List<DevicePcbExFactorySimPoolInfo> simPoolList = devicePcbExFactorySimPoolInfoService.getAllList(getDevicePcbExFactorySimPoolInfoDO);
        if (simPoolList.size() > 0) {
            for (DevicePcbExFactorySimPoolInfo info : simPoolList) {
                info.setStatus(1);//已出厂
                info.setLastModifiedTime(new Date());
                updateSimPoolList.add(info);
            }
            devicePcbExFactorySimPoolInfoService.updateList(updateSimPoolList);
        }
        DevicePcbExFactoryScanRecordInfo recordInfo = new DevicePcbExFactoryScanRecordInfo();
        recordInfo.setBatchId(batchInfo.getBatchId());
        recordInfo.setCartonNo(dto.getCartonNo());
        recordInfo.setPassDtus(dto.getDtus());
        recordInfo.setNoPassDtus(dto.getNoPassDtus());
        devicePcbExFactoryScanRecordInfoService.save(recordInfo);
        return Result.suc();
    }

    @Log(title = "PCB终端管理-工位机三码验证", businessType = BusinessType.DELETE)
    @ApiOperation(value = "工位机三码验证")
    @GetMapping("/vail3Code")
    public Result<Vail3CodeVO> vail3Code(@RequestParam String dtu, @RequestParam String imei, @RequestParam String sim) {
        Vail3CodeVO vo = new Vail3CodeVO();
        if (StringUtils.isBlank(dtu) || StringUtils.isBlank(imei) || StringUtils.isBlank(sim)) {
            vo.setStatus(false);
            vo.setMsg("设备编号或IMEI或SIM号为空");
            return Result.suc(vo);
        }

        if (devicePcbBjBaseInfoService.getByDtu(dtu) != null) {
            vo.setStatus(false);
            vo.setMsg("设备编号已经存在");
            return Result.suc(vo);
        }
        if (devicePcbBjBaseInfoService.getBySim(sim) != null) {
            vo.setStatus(false);
            vo.setMsg("SIM卡号已经存在");
            return Result.suc(vo);
        }
        DevicePcbBjBaseInfo info = new DevicePcbBjBaseInfo();
        info.setDtu(dtu);
        info.setSim(sim);
        devicePcbBjBaseInfoService.save(info);
        return Result.suc(vo);
    }

    private Map<String, String> getSensorMap() {
        Map<String, String> map = new HashMap<>();
        map.put("5523", "保护性耕作");
        map.put("5525", "深松");
        map.put("552C", "深翻");
        map.put("552D", "收获");
        map.put("552H", "旋耕");
        map.put("5527", "打捆");
        map.put("552B", "植保");
        map.put("552L", "施肥");
        map.put("552M", "残膜");
        map.put("552I", "靶地");
        map.put("552G", "种植");
        map.put("552Y", "作业监测");
        map.put("552F", "水稻插秧");
        return map;
    }
}
